package com.itheima.cookie.cookietest2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

//通过第一次访问cookie判断是否为第一次访问
@WebServlet("/lastTimeCookie")
public class CookieDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取名为lastTimeCookie的对象
        Cookie[] cookies = req.getCookies();

        //定义一个cookie,遍历cookies
        Cookie cookie = null;

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();

        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("lastTimeCookie".equals(c.getName())) {
                    cookie = c;
                    break;
                }
            }
        }

        if (cookie == null) {
            pw.write("<h4>欢迎首次访问!</h4>");
        } else {
            //如果有就不是第一次访问,根据cookie获得值
            String value = cookie.getValue();
            pw.write("<h4>欢迎回来,您上次登录时间是:" + value +"</h4>");
        }
        Cookie ck = new Cookie("lastTimeCookie", new Date().toLocaleString().replace(" ", ""));

        //持久化保存
        ck.setMaxAge(24*60*60);

        //添加到浏览器
        resp.addCookie(ck);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
